// 通用功能模块

// 显示状态提示
function showStatus(message, type = 'info') {
    // 移除现有的所有提示框
    const existingToasts = document.querySelectorAll('.toast');
    existingToasts.forEach(toast => toast.remove());

    // 创建提示框
    const toast = document.createElement('div');
    toast.className = `toast toast-${type}`;

    // 设置图标
    let iconClass = 'fas fa-info-circle';
    if (type === 'success') iconClass = 'fas fa-check-circle';
    else if (type === 'error') iconClass = 'fas fa-exclamation-circle';
    else if (type === 'warning') iconClass = 'fas fa-exclamation-triangle';
    else if (type === 'loading') iconClass = 'fas fa-spinner fa-spin';

    // 设置提示框内容
    toast.innerHTML = `
        <div class="toast-icon">
            <i class="${iconClass}"></i>
        </div>
        <div class="toast-message">${message}</div>
        <button class="toast-close">
            <i class="fas fa-times"></i>
        </button>
    `;

    // 添加到文档
    document.body.appendChild(toast);

    // 设置位置 - 右下角
    toast.style.position = 'fixed';
    toast.style.right = '20px';
    toast.style.bottom = '20px';
    toast.style.zIndex = '10000';
    toast.style.transform = 'translateY(20px)';
    toast.style.opacity = '0';
    toast.style.transition = 'transform 0.3s ease, opacity 0.3s ease';

    // 显示动画
    setTimeout(() => {
        toast.style.transform = 'translateY(0)';
        toast.style.opacity = '1';
    }, 10);

    // 关闭按钮事件
    const closeButton = toast.querySelector('.toast-close');
    closeButton.addEventListener('click', () => {
        toast.style.transform = 'translateY(20px)';
        toast.style.opacity = '0';
        setTimeout(() => {
            toast.remove();
        }, 300);
    });

    // 自动关闭（loading类型不自动关闭）
    if (type !== 'loading') {
        setTimeout(() => {
            toast.style.transform = 'translateY(20px)';
            toast.style.opacity = '0';
            setTimeout(() => {
                toast.remove();
            }, 300);
        }, 3000);
    }

    return toast;
}

// 生成静态内容
function generateContent(type) {
    // 禁用生成按钮
    const generateBtns = document.querySelectorAll('.generate-btn');
    generateBtns.forEach(btn => {
        btn.disabled = true;
        btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 生成中...';
    });

    // 显示生成状态
    showStatus('正在生成' + (type === 'index' ? '首页' : type === 'posts' ? '帖子' : '分区') + '静态内容...', 'loading');

    fetch('../BlogMake.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: 'action=generate_content&type=' + type
    })
        .then(response => response.json())
        .then(data => {
            // 恢复生成按钮
            generateBtns.forEach(btn => {
                btn.disabled = false;
                btn.innerHTML = '<i class="fas fa-magic"></i> 生成';
            });

            if (data.success) {
                showStatus('生成' + (type === 'index' ? '首页' : type === 'posts' ? '帖子' : '分区') + '静态内容成功', 'success');
            } else {
                showStatus('生成失败: ' + data.message, 'error');
            }
        })
        .catch(error => {
            // 恢复生成按钮
            generateBtns.forEach(btn => {
                btn.disabled = false;
                btn.innerHTML = '<i class="fas fa-magic"></i> 生成';
            });

            console.error('生成内容失败:', error);
            showStatus('生成内容失败', 'error');
        });
}

// 初始化选项卡
function initTabs() {
    // 获取所有选项卡和侧边栏菜单
    const tabButtons = document.querySelectorAll('.tab');
    const navLinks = document.querySelectorAll('.nav-link');
    
    // 切换选项卡的通用函数
    function switchTab(targetId) {
        // 移除所有选项卡的active类
        tabButtons.forEach(btn => btn.classList.remove('active'));
        
        // 移除所有侧边栏菜单的active类
        navLinks.forEach(link => link.classList.remove('active'));

        // 给对应的选项卡添加active类
        const activeTab = document.querySelector(`.tab[data-target="${targetId}"]`);
        if (activeTab) {
            activeTab.classList.add('active');
        }
        
        // 给对应的侧边栏菜单添加active类
        const activeNav = document.querySelector(`.nav-link[data-target="${targetId}"]`);
        if (activeNav) {
            activeNav.classList.add('active');
        }

        // 隐藏所有内容区域
        const tabContents = document.querySelectorAll('.tab-content');
        tabContents.forEach(content => content.style.display = 'none');

        // 显示当前内容区域
        const tabElement = document.getElementById(targetId);
        if (tabElement) {
            tabElement.style.display = 'block';
        }

        // 如果是博客列表或作品列表，加载数据
        if (targetId === 'blog-panel') {
            loadBlogList();
        } else if (targetId === 'works-panel') {
            loadWorksList();
        } else if (targetId === 'partition-panel') {
            loadPartitionList();
        }
    }
    
    // 选项卡切换
    tabButtons.forEach(button => {
        button.addEventListener('click', function () {
            const tabId = this.getAttribute('data-target');
            switchTab(tabId);
        });
    });
    
    // 侧边栏菜单切换
    navLinks.forEach(link => {
        link.addEventListener('click', function (e) {
            e.preventDefault();
            const tabId = this.getAttribute('data-target');
            switchTab(tabId);
        });
    });

    // 默认激活第一个选项卡
    if (tabButtons.length > 0) {
        tabButtons[0].click();
    }
}

// 数据缓存管理
const dataCache = {
    works: null,
    partitions: null,
    blogs: null,
    cacheTime: 0,
    cacheDuration: 30000, // 缓存30秒
    
    isCacheValid() {
        return Date.now() - this.cacheTime < this.cacheDuration;
    },
    
    updateCache(dataType, data) {
        this[dataType] = data;
        this.cacheTime = Date.now();
    },
    
    getCache(dataType) {
        if (this.isCacheValid() && this[dataType]) {
            return this[dataType];
        }
        return null;
    }
};

// 模态框管理器
const modalManager = {
    // 打开模态框
    open(modalId, options = {}) {
        const modal = document.getElementById(modalId);
        if (!modal) return;
        
        // 设置标题
        if (options.title && modal.querySelector('.modal-title')) {
            modal.querySelector('.modal-title').textContent = options.title;
        }
        
        // 清空表单
        if (options.clearForm !== false) {
            const form = modal.querySelector('form');
            if (form) {
                form.reset();
                // 清空隐藏字段
                form.querySelectorAll('input[type="hidden"]').forEach(input => {
                    input.value = '';
                });
            }
        }
        
        // 填充数据
        if (options.data) {
            this.fillData(modalId, options.data);
        }
        
        // 显示模态框
        modal.style.display = 'flex';
        
        // 添加回调
        if (options.onOpen && typeof options.onOpen === 'function') {
            options.onOpen(modal);
        }
        
        return modal;
    },
    
    // 关闭模态框
    close(modalId) {
        const modal = document.getElementById(modalId);
        if (modal) {
            modal.style.display = 'none';
        }
    },
    
    // 填充数据到模态框
    fillData(modalId, data) {
        const modal = document.getElementById(modalId);
        if (!modal || !data) return;
        
        Object.keys(data).forEach(key => {
            const element = modal.querySelector(`[name="${key}"], #${modalId.split('-')[0]}-${key}`);
            if (element) {
                if (element.tagName === 'INPUT' || element.tagName === 'TEXTAREA' || element.tagName === 'SELECT') {
                    element.value = data[key] || '';
                }
            }
        });
    },
    
    // 初始化模态框事件
    init() {
        // 为所有带有 close-modal 类的元素添加点击事件
        const closeButtons = document.querySelectorAll('.close-modal');
        closeButtons.forEach(button => {
            button.addEventListener('click', function() {
                const modal = this.closest('.modal');
                if (modal) {
                    modal.style.display = 'none';
                }
            });
        });
        
        // 点击模态框背景关闭
        document.addEventListener('click', function (e) {
            if (e.target.classList.contains('modal') && !e.target.classList.contains('modal-content')) {
                e.target.style.display = 'none';
            }
        });
        
        // 点击模态框内容区域不关闭
        const modalContents = document.querySelectorAll('.modal-content');
        modalContents.forEach(content => {
            content.addEventListener('click', function (e) {
                e.stopPropagation();
            });
        });
        
        // ESC键关闭模态框
        document.addEventListener('keydown', function (e) {
            if (e.key === 'Escape') {
                const modals = document.querySelectorAll('.modal[style*="display: flex"]');
                modals.forEach(modal => {
                    modal.style.display = 'none';
                });
            }
        });
    }
};

// 初始化模态框
function initModals() {
    modalManager.init();
}

// 初始化按钮事件
function initButtons() {
    // 登录按钮
    document.getElementById('login-btn')?.addEventListener('click', function () {
        login();
    });

    // 退出登录按钮
    document.getElementById('logout-btn')?.addEventListener('click', function () {
        logout();
    });

    // 打开新建帖子按钮
    document.getElementById('new-post-btn')?.addEventListener('click', function () {
        openPostEditor();
    });

    // 添加Works按钮
    document.getElementById('add-work-btn')?.addEventListener('click', function () {
        openWorkEditor();
    });

    // 添加分区按钮
    document.getElementById('add-partition-btn')?.addEventListener('click', function () {
        openPartitionModal();
    });

    // 生成首页按钮
    document.getElementById('generate-index')?.addEventListener('click', function () {
        generateContent('index');
    });

    // 生成所有帖子按钮
    document.getElementById('generate-posts')?.addEventListener('click', function () {
        generateContent('posts');
    });

    // 生成所有分区按钮
    document.getElementById('generate-partitions')?.addEventListener('click', function () {
        generateContent('partitions');
    });
}

// 初始化表单
function initForms() {
    // 登录表单提交
    const loginForm = document.getElementById('login-form');
    if (loginForm) {
        loginForm.addEventListener('submit', function (e) {
            e.preventDefault();
            const username = document.getElementById('username').value;
            const password = document.getElementById('password').value;
            login(username, password);
        });
    }

    // 站点配置表单提交
    const siteConfigForm = document.getElementById('site-config-form');
    if (siteConfigForm) {
        // 为表单添加提交事件
        siteConfigForm.addEventListener('submit', function (e) {
            e.preventDefault();
            saveSiteConfig();
        });
        
        // 为保存按钮添加直接点击事件，作为后备机制
        const saveButton = siteConfigForm.querySelector('button[type="submit"]');
        if (saveButton) {
            saveButton.addEventListener('click', function (e) {
                e.preventDefault();
                saveSiteConfig();
            });
        }
    }

    // 分区表单提交
    const partitionForm = document.getElementById('partition-form');
    if (partitionForm) {
        partitionForm.addEventListener('submit', function (e) {
            e.preventDefault();
            savePartition();
        });
    }
}